package com.longkier.gx_library_springboot.BigModelSocket;

import org.jetbrains.annotations.NotNull;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.TextMessage;
import org.springframework.stereotype.Component;

@Component
public class WebSocketController extends TextWebSocketHandler {

    @Override
    public void handleTextMessage(@NotNull WebSocketSession session, @NotNull TextMessage message) throws Exception {
        BigModelNew.NewQuestion = message.getPayload();
        // 将前端session传递给大模型处理器
        BigModelNew wsHandler = new BigModelNew("user123", false, null, session);
        wsHandler.processQuestion(); // 开始处理消息

        // 由于 onOpen 是异步操作，我们可以在这里等待模型返回后再发送响应
        String responseMessage = BigModelNew.totalAnswer;  // 获取模型的回答

        // 发送处理结果给前端
        session.sendMessage(new TextMessage(responseMessage));
    }

    @Override
    public void afterConnectionEstablished(@NotNull WebSocketSession session) throws Exception {
        // WebSocket连接建立时的初始化操作
        System.out.println("WebSocket连接已建立: " + session.getId());
    }

    @Override
    public void handleTransportError(@NotNull WebSocketSession session, @NotNull Throwable exception) throws Exception {
        // 处理 WebSocket 连接错误
        System.err.println("WebSocket 连接错误: " + exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(@NotNull WebSocketSession session, org.springframework.web.socket.@NotNull CloseStatus status) throws Exception {
        // WebSocket 连接关闭时的清理操作
        System.out.println("WebSocket连接已关闭: " + session.getId());
    }
}
